<?php

namespace App\Http\Middleware;

//use App\Models\VueAdmin as Admin;
use App\Exceptions\ParameterException;

use App\Models\VueAdminMenu;
use App\Models\VueAdminRole;
use App\Models\VueAdminRoleUser;
use Closure;

class Permission
{
    const CODE_AUTHFAIL = 401;

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('token');
        if (!$token) {
            $token = $request->input('token'); // 调试用
        }
        if (!$token) {
            throw new ParameterException([
                'code' => self::CODE_AUTHFAIL,
                'msg' => 'token 不能为空！'
            ]);
        }
        $jwt_data = \App\Services\AuthToken::verify($token);
        if (!$jwt_data || !$jwt_data->admin_id) {
            throw new ParameterException([
                'code' => self::CODE_AUTHFAIL,
                'msg' => '登录状态已过期！',
            ]);
        }
        $admin = cache('auth_admin_id-' . $jwt_data->admin_id);
        if (!$admin) {
            throw new ParameterException([
                'code' => self::CODE_AUTHFAIL,
                'msg' => 'token值已过期，请重新登录！'
            ]);
        }
        // 获取url 不带域名
        $url = $request->path();
        // adminapi/vm/shoutDown
        $url = str_replace('adminapi/', '', $url);
        logInfo('test', $url);
        if ($url == 'admin/profile') {
            return $next($request);
        } else {
            if ($admin['id'] != 1) {
                $roleId = VueAdminRoleUser::where('admin_id', $admin['id'])->value('role_id');
                $permission = VueAdminRole::query()->where('id', $roleId)->first()->toArray();
                $son_access = explode(',', $permission['access']);
                $p_access = explode(',', $permission['p_access']);
                $access = array_merge($son_access, $p_access);

                $routeArr = explode('/', trim($url, '/'));
                $action = $routeArr[1];
                $route = $url;
                if ($action == 'list') {
                    $action = 'index';
                    $route = $routeArr[0];
                } elseif ($action == 'save') {
                    $action = 'add';
                    $route = str_replace('save', $action, $route);
                } elseif ($action == 'info') {
                    $action = 'edit';
                    $route = str_replace('info', $action, $route);
                }
                logInfo('permission', $request->path());
                logInfo('permission', $route, 'route');
                logInfo('permission', $action, 'action');
                logInfo('permission', $access, 'access');
                $id = VueAdminMenu::query()->where('route', $route)->where('action', $action)->value('id');
                // logInfo('permission',$id,'id');
                if (!in_array($id, $access)) {
                    throw new ParameterException([
                        'code' => 400,
                        'msg' => '您没有权限！'
                    ]);
                }

            }
        }

        return $next($request);
    }
}
